<template>
  <el-table size="small" :data="data.data" height="100%" v-loading="loading" highlight-current-row stripe border>
    <el-table-column type="index" width="60" label="序号" align="center" v-if="!!table" fixed />
    <el-table-column min-width="80px" v-for="col in data.columns" :label="columnInfo[col].name"
      :width="columnInfo[col].width" :align="columnInfo[col].align" :key="col" :prop="col" :fixed="col === 'COLUMN_NAME'">
      <template #default="{ row }">
        <span class="null-cell" v-if="row[col] === null">NULL</span>
        <span class="value-cell" :title="row[col]" v-else>
          <span v-if="col === 'COLUMN_KEY' && row[col] === 'PRI'">主键</span>
          <span v-else-if="col === 'COLUMN_KEY' && row[col] === 'UNI'">唯一</span>
          <span v-else-if="col === 'EXTRA' && row[col] === 'auto_increment'">自增</span>
          <span v-else>{{ row[col] }}</span>
        </span>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import utils from "@/assets/scripts/utils";
import { ElMessage } from "element-plus";
import apis from '@/assets/apis'

export default {
  name: "TableColumns",
  props: {
    table: String
  },
  data() {
    return {
      data: {},
      loading: false,
      columnInfo: {
        COLUMN_NAME: {
          name: '名称',
          width: 200
        },
        IS_NULLABLE: {
          name: '允许 NULL',
          width: 80
        },
        COLUMN_DEFAULT: {
          name: '默认值',
          width: 140
        },
        COLUMN_TYPE: {
          name: '类型',
          width: 140
        },
        COLUMN_KEY: {
          name: '键',
          width: 80
        },
        EXTRA: {
          name: '其它属性',
          width: 160
        },
        COLUMN_COMMENT: {
          name: '说明'
        },
      }
    }
  },
  mounted() {
    if (this.table) {
      this.load()
    }
  },
  watch: {
    table(v) {
      if (v) {
        this.load()
      }
    }
  },
  methods: {
    load() {
      this.loading = true
      this.$store.commit('updateGlobalMsg', '正在加载表信息...')
      apis.dbm.table.getColumns(this.table).then(data => {
        this.data = utils.parseDatatable(data[0])
        this.$store.commit('updateGlobalMsg', '加载完成')
      }).catch(e => {
        this.$store.commit('updateGlobalMsg', `错误： ${e.message}`)
        ElMessage.error(e.message)
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
